package com.atguigu.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.realtime.app.BaseAppV2;
import com.atguigu.realtime.bean.OrderWide;
import com.atguigu.realtime.bean.PaymentWide;
import com.atguigu.realtime.bean.ProductStats;
import com.atguigu.realtime.common.Constant;
import com.atguigu.realtime.function.DimAsyncFunction;
import com.atguigu.realtime.util.AtguiguUtil;
import com.atguigu.realtime.util.DimUtil;
import com.atguigu.realtime.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.streaming.api.datastream.AsyncDataStream;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.async.ResultFuture;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;
import redis.clients.jedis.Jedis;

import java.sql.Connection;
import java.time.Duration;
import java.util.Collections;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2022/2/18 8:56
 */
public class DwsProductApp extends BaseAppV2 {
    public static void main(String[] args) {
        /*
        点击	多维分析	dwd_page_log直接可求	dwd
        曝光	多维分析	dwd_display_log直接可求	dwd
        收藏	多维分析	收藏表	dwd
        加入购物车	多维分析	购物车表	dwd
        下单	可视化大屏	订单宽表	dwm
        支付	多维分析	支付宽表	dwm
        退款	多维分析	退款表	dwd
        评价	多维分析	评价表	dwd

         */
        new DwsProductApp().init(4002, 1, "DwsProductApp", "DwsProductApp",
                                 Constant.TOPIC_DWD_PAGE, Constant.TOPIC_DWD_DISPLAY,
                                 Constant.TOPIC_DWD_FAVOR_INFO, Constant.TOPIC_DWD_CART_INFO,
                                 Constant.TOPIC_DWM_ORDER_WIDE, Constant.TOPIC_DWM_PAYMENT_WIDE,
                                 Constant.TOPIC_DWD_ORDER_REFUND_INFO, Constant.TOPIC_DWD_COMMENT_INFO);
    }
    
    @Override
    protected void run(StreamExecutionEnvironment env, Map<String, DataStreamSource<String>> topicStreamMap) {
        // 1. 解析数据, 然后union成一个流
        DataStream<ProductStats> psStream = parseAndUnionOne(topicStreamMap);
        // 2. 开窗聚合
        SingleOutputStreamOperator<ProductStats> aggregatedStream = aggregate(psStream);
        // 3. 补充维度
        SingleOutputStreamOperator<ProductStats> psStreamWithDim = joinDim(aggregatedStream);
    
        // 4. 把数据写入到ClickHouse中
        write2ClickHouse(psStreamWithDim);
        
        // 5. 需要把商品主题宽表数据另写一分到Kafka, 给商品行为关键词主题使用
        write2Kafka(psStreamWithDim);
    }
    
    private void write2Kafka(SingleOutputStreamOperator<ProductStats> psStreamWithDim) {
        psStreamWithDim
            .map(JSON::toJSONString)
            .addSink(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWS_PRODUCT));
    }
    
    private void write2ClickHouse(SingleOutputStreamOperator<ProductStats> stream) {
    
        stream.addSink(FlinkSinkUtil.getClickHouseSink("gmall2022", "product_stats_2022", ProductStats.class));
    }
    
    private SingleOutputStreamOperator<ProductStats> joinDim(SingleOutputStreamOperator<ProductStats> aggregatedStream) {
        /*
        能不能直接从订单宽表或者支付宽表获取维度信息?
            不行. 原因是有些商品没有被下单或者支付
         */
      return  AsyncDataStream.unorderedWait(
            aggregatedStream,
            new DimAsyncFunction<ProductStats>() {
                @Override
                protected void addDim(Jedis redisClient,
                                      Connection conn,
                                      ProductStats ps,
                                      ResultFuture<ProductStats> resultFuture) throws Exception {
                    // 补充4张和商品相关的维度
                    // 3. sku_info  一定要先查sku_info, 这样才能查到spu_id, 然后再根据spu_id去spu_info中查spu_name
                    JSONObject skuInfo = DimUtil.readDim(redisClient, conn, "dim_sku_info", ps.getSku_id());  // alt+R
                    ps.setSku_name(skuInfo.getString("SKU_NAME"));
                    ps.setSku_price(skuInfo.getBigDecimal("PRICE"));
    
    
                    ps.setSpu_id(skuInfo.getLong("SPU_ID"));
                    ps.setTm_id(skuInfo.getLong("TM_ID"));
                    ps.setCategory3_id(skuInfo.getLong("CATEGORY3_ID"));
    
                    // 4. spu_info
                    JSONObject spuInfo = DimUtil.readDim(redisClient,conn, "dim_spu_info", ps.getSpu_id());
                    ps.setSpu_name(spuInfo.getString("SPU_NAME"));
    
                    // 5. base_trademark
                    JSONObject baseTrademark = DimUtil.readDim(redisClient,conn, "dim_base_trademark", ps.getTm_id());
                    ps.setTm_name(baseTrademark.getString("TM_NAME"));
    
                    // 6. c3
                    JSONObject baseCategory3 = DimUtil.readDim(redisClient,conn, "dim_base_category3", ps.getCategory3_id());
                    ps.setCategory3_name(baseCategory3.getString("NAME"));
    
    
                    // 把补完维度数据orderWide放入到后面的流中
                    resultFuture.complete(Collections.singletonList(ps));
                    
                }
            },
            30,
            TimeUnit.SECONDS
        );
    }
    
    private SingleOutputStreamOperator<ProductStats> aggregate(DataStream<ProductStats> psStream) {
        return psStream
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<ProductStats>forBoundedOutOfOrderness(Duration.ofSeconds(20))
                    .withTimestampAssigner((ps, ts) -> ps.getTs())
            )
            .keyBy(ProductStats::getSku_id)
            .window(TumblingEventTimeWindows.of(Time.seconds(5)))
            .reduce(
                new ReduceFunction<ProductStats>() {
                    @Override
                    public ProductStats reduce(ProductStats ps1,
                                               ProductStats ps2) throws Exception {
                        ps1.setClick_ct(ps1.getClick_ct() + ps2.getClick_ct());
                        ps1.setDisplay_ct(ps1.getDisplay_ct() + ps2.getDisplay_ct());
                        ps1.setFavor_ct(ps1.getFavor_ct() + ps2.getFavor_ct());
                        ps1.setCart_ct(ps1.getCart_ct() + ps2.getClick_ct());
                        ps1.setGood_comment_ct(ps1.getGood_comment_ct() + ps2.getGood_comment_ct());
                        ps1.setComment_ct(ps1.getComment_ct() + ps2.getComment_ct());
                        
                        ps1.setOrder_amount(ps1.getOrder_amount().add(ps2.getOrder_amount()));
                        ps1.setPayment_amount(ps1.getPayment_amount().add(ps2.getPayment_amount()));
                        ps1.setRefund_amount(ps1.getRefund_amount().add(ps2.getRefund_amount()));
                        
                        ps1.setOrder_sku_num(ps1.getOrder_sku_num() + ps2.getOrder_sku_num());
                        
                        ps1.getOrderIdSet().addAll(ps2.getOrderIdSet());
                        ps1.getPaidOrderIdSet().addAll(ps2.getPaidOrderIdSet());
                        ps1.getRefundOrderIdSet().addAll(ps2.getRefundOrderIdSet());
                        
                        return ps1;
                    }
                },
                new ProcessWindowFunction<ProductStats, ProductStats, Long, TimeWindow>() {
                    @Override
                    public void process(Long key,
                                        Context ctx,
                                        Iterable<ProductStats> elements,
                                        Collector<ProductStats> out) throws Exception {
                        // stt和edt补充
                        String stt = AtguiguUtil.toDateTime(ctx.window().getStart());
                        String edt = AtguiguUtil.toDateTime(ctx.window().getEnd());
                        // 订单 支付 退款  订单数的计算
                        ProductStats ps = elements.iterator().next();
                        ps.setStt(stt);
                        ps.setEdt(edt);
                        
                        ps.setOrder_ct((long) ps.getOrderIdSet().size());
                        ps.setPaid_order_ct((long) ps.getPaidOrderIdSet().size());
                        ps.setRefund_order_ct((long) ps.getRefundOrderIdSet().size());
    
                        ps.setTs(System.currentTimeMillis());
                        
                        out.collect(ps);
                        
                    }
                }
            );
    }
    
    private DataStream<ProductStats> parseAndUnionOne(Map<String, DataStreamSource<String>> topicStreamMap) {
        
        // 1. 点击
        SingleOutputStreamOperator<ProductStats> clickStream = topicStreamMap
            .get(Constant.TOPIC_DWD_PAGE)
            .flatMap(new FlatMapFunction<String, ProductStats>() {
                @Override
                public void flatMap(String value,
                                    Collector<ProductStats> out) throws Exception {
                    JSONObject obj = JSON.parseObject(value);
                    
                    JSONObject page = obj.getJSONObject("page");
                    
                    String itemType = page.getString("item_type");
                    if ("sku_id".equals(itemType)) {
                        
                        Long skuId = page.getLong("item");
                        
                        ProductStats ps = new ProductStats();
                        ps.setSku_id(skuId);
                        ps.setClick_ct(1L);
                        ps.setTs(obj.getLong("ts"));
                        out.collect(ps);
                        
                    }
                }
            });
        
        // 2. 曝光
        SingleOutputStreamOperator<ProductStats> displayStream = topicStreamMap
            .get(Constant.TOPIC_DWD_DISPLAY)
            .filter(json -> "sku_id".equals(JSON.parseObject(json).getString("item_type")))
            .map(json -> {
                JSONObject obj = JSON.parseObject(json);
                
                ProductStats ps = new ProductStats();
                ps.setSku_id(obj.getLong("item"));
                ps.setDisplay_ct(1L);
                ps.setTs(obj.getLong("ts"));
                
                return ps;
                
            });
        
        // 3. 收藏
        SingleOutputStreamOperator<ProductStats> favorStream = topicStreamMap
            .get(Constant.TOPIC_DWD_FAVOR_INFO)
            .map(json -> {
                JSONObject obj = JSON.parseObject(json);
                
                ProductStats ps = new ProductStats();
                ps.setSku_id(obj.getLong("sku_id"));
                ps.setFavor_ct(1L);
                ps.setTs(AtguiguUtil.toTs(obj.getString("create_time")));
                return ps;
            });
        
        // 4. 加购
        SingleOutputStreamOperator<ProductStats> cartStream = topicStreamMap
            .get(Constant.TOPIC_DWD_CART_INFO)
            .map(json -> {
                JSONObject obj = JSON.parseObject(json);
                
                ProductStats ps = new ProductStats();
                ps.setSku_id(obj.getLong("sku_id"));
                ps.setCart_ct(1L);
                ps.setTs(AtguiguUtil.toTs(obj.getString("create_time")));
                return ps;
            });
        
        // 5. 订单
        SingleOutputStreamOperator<ProductStats> orderStream = topicStreamMap
            .get(Constant.TOPIC_DWM_ORDER_WIDE)
            .map(json -> {
                OrderWide orderWide = JSON.parseObject(json, OrderWide.class);
                
                ProductStats ps = new ProductStats();
                ps.setSku_id(orderWide.getSku_id());
                
                ps.setOrder_amount(orderWide.getSplit_total_amount());
                ps.setOrder_sku_num(orderWide.getSku_num());
                
                ps.getOrderIdSet().add(orderWide.getOrder_id());
                
                ps.setTs(AtguiguUtil.toTs(orderWide.getCreate_time()));
                
                return ps;
            });
        
        // 6. 支付
        SingleOutputStreamOperator<ProductStats> paymentStream = topicStreamMap
            .get(Constant.TOPIC_DWM_PAYMENT_WIDE)
            .map(json -> {
                PaymentWide paymentWide = JSON.parseObject(json, PaymentWide.class);
                
                ProductStats ps = new ProductStats();
                
                ps.setSku_id(paymentWide.getSku_id());
                
                ps.setPayment_amount(paymentWide.getSplit_total_amount());
                ps.getPaidOrderIdSet().add(paymentWide.getOrder_id());
                
                ps.setTs(AtguiguUtil.toTs(paymentWide.getPayment_create_time()));
                
                return ps;
            });
        
        // 7. 退款
        SingleOutputStreamOperator<ProductStats> refundStream = topicStreamMap
            .get(Constant.TOPIC_DWD_ORDER_REFUND_INFO)
            .map(json -> {
                JSONObject obj = JSON.parseObject(json);
                
                ProductStats ps = new ProductStats();
                ps.setSku_id(obj.getLong("sku_id"));
                
                ps.setRefund_amount(obj.getBigDecimal("refund_amount"));
                
                ps.getRefundOrderIdSet().add(obj.getLong("order_id"));
                
                ps.setTs(AtguiguUtil.toTs(obj.getString("create_time")));
                
                return ps;
            });
        
        // 8. 评价
        
        SingleOutputStreamOperator<ProductStats> commentStream = topicStreamMap
            .get(Constant.TOPIC_DWD_COMMENT_INFO)
            .map(json -> {
                JSONObject obj = JSON.parseObject(json);
                
                ProductStats ps = new ProductStats();
                ps.setSku_id(obj.getLong("sku_id"));
                ps.setComment_ct(1L);
                
                String appraise = obj.getString("appraise");
                
                if (Constant.FIVE_STAR_GOOD_COMMENT.equals(appraise)
                    || Constant.FOUR_STAR_GOOD_COMMENT.equals(appraise)) {
                    ps.setGood_comment_ct(1L);
                    
                }
                
                ps.setTs(AtguiguUtil.toTs(obj.getString("create_time")));
                
                return ps;
            });
        
        return clickStream.union(
            displayStream,
            favorStream,
            cartStream,
            orderStream,
            paymentStream,
            refundStream,
            commentStream
        );
    }
}
